document.write('<div id="loading">Loading...</div>');

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  document.getElementById("loading").style.display="none";
});
/* **********************************************
 * BOOT Process Handlers
 * **********************************************/
Event.observe(window, 'load', function()
									{ bindEvents();
									  bootDot();
									});

function bootDot(){
	updateWrapperSize(); 
	setGlobalDivCounter("wrapper");
	fileBrowser_init();
	makeColorSelectors();
	if (document.all && window.print) {
		document.oncontextmenu = ieClickHandler;
	}
	//hiding the file browser if IE
	if(Util.getBrowser().indexOf("ie") != -1)
	{
	    $('fileBrowserWindow_header').hide();
		$('fileBrowserWindow_header_li').hide();
	}
	
	//making the control panel sortable
	Sortable.create("headerList",
	     {dropOnEmpty:true,constraint:false,ghosting:false});
	
	//load calendar files
	//loadCalendar();
}

isOfType = function(element, type){
	if(element && element.tagName){
		return (element.tagName.toLowerCase() == type);
	}else{
		return false;
	}
	
};

function isAccepted(element){
	if(element){
		if(element.id && (element.id == "header" || element.id == "footer")){
			return false;
		}else{
			if( ($(element).descendantOf('header')) || ($(element).descendantOf('footer')) ){
				return false;
			}
		}
		return true;
	}
	return false;
}

function setGlobalDivCounter(divid){
	var divList = $(divid).childNodes;
	/*if(divList.length == 0){return; }*/
	var count = 0;
	while(count < divList.length)
	{
		var divElement = divList.item(count);
		if(isOfType(divElement,'div'))
		{
			var idValue = divElement.id;
			if(idValue != "header" && idValue != "footer")
			{
				divCounter++;
				/*if(globalDivArray.get(idValue) === "")
				{
					globalDivArray.put(idValue,new Draggable(''+idValue, {}));
					setGlobalDivCounter(idValue);	
				}*/
			}
		}
		count++;
	}
	return;
}

function updateWrapperSize(){
	//$("fileBrowserBucket").style.height = (window.innerHeight-200) + 'px';
	if(Util.getBrowser().indexOf("ie",0) != -1){
		$("wrapper").style.height = document.documentElement.clientHeight + 'px';
		$("wrapper").style.width = document.documentElement.clientWidth + 'px';
	}else{
		$("wrapper").style.height = window.innerHeight + 'px';
		$("wrapper").style.width = window.innerWidth + 'px';
	}
}

/* disable the usual left mouse menu (back, forward, reload, etc)*/
window.oncontextmenu = function() {return false;}; /* FIREFOX */
/* IE */
// document.oncontextmenu = function(){ return false; }

/* **********************************************
 * Right click Menu Handlers
 * **********************************************/
function ieClickHandler(){
	displayRightClickMenu(window.event);
	/*
	var divID = "divMenuNew";
			var div = $(divID);
			var rightedge = document.body.clientWidth-event.clientX;
			var bottomedge = document.body.clientHeight-event.clientY;
			if (rightedge < div.offsetWidth){
				div.style.left = document.body.scrollLeft + event.clientX - div.offsetWidth;
			}else{
				div.style.left = document.body.scrollLeft + event.clientX;
			}
			
			if (bottomedge < div.offsetHeight){
				div.style.top = document.body.scrollTop + event.clientY - div.offsetHeight;
			}else{
				div.style.top = document.body.scrollTop + event.clientY;
			}
			div.style.display = "block";*/
		
			return false;
}

function clickHandler(e, object){
	var browser = Util.getBrowser();
	if(browser.indexOf("NN") != -1){ //if firefox
		mouseDown(e,object);
	}else{ //if IE
		
	}
}

function mouseDown(e,object){
        if (menuDisplayed) {
           Util.hideMenu(); menuDisplayed = false;
        }

        if (isRightClick(e)) {
             //displayMenu(e);
			 activateElement(e);
             menuDisplayed = true;
        } else {
               if (object == window && 
                   e.target.attributes.getNamedItem('action')) {
                eval(e.target.attributes.getNamedItem('action').value);
               }
        }
 }

function setGlobalEvent(event){
	/* PREVIOUS */
	globalPrevEvent = globalEvent;
	globalPrevPositionX = globalPositionX;
	globalPrevPositionY = globalPositionY;
	
	globalEvent = event;
	globalPositionX = Event.pointerX(event);
	globalPositionY = Event.pointerY(event);
	//alert(globalPositionX + "," + globalPositionY);
}

function activateElement(e){
	if(Event.element(e)){ //event
		if( isAccepted(Event.element(e)) ){
			disableResizable();
			if(Event.element(e)){
				window.currentObject = Event.element(e);
				setGlobalEvent(e);
			}
			//alert(currentObject.id);
			if(isOfType(currentObject,"span")===false && currentObject.id && currentObject.id != "wrapper"){
				enableResizable();
			}
			//if(currentObject.id && currentObject.id != "wrapper"){
				selectElement(currentObject.id);
			//}
		}
	}else{ //object
		disableResizable();
		currentObject = e;
		if(isOfType(currentObject,"span")===false && currentObject.id && currentObject.id != "wrapper"){
			enableResizable();
		}
		selectElement(currentObject.id);
	}
}


function displayRightClickMenu(e) {
    Util.hideMenu();
	
	disableResizable();
	window.currentObject = Event.element(e);
	setGlobalEvent(e);
	
	if(currentObject.id && currentObject.id != "wrapper"){
		enableResizable();
	}
	//if(currentObject.id && currentObject.id != "wrapper"){
		selectElement(currentObject.id);
	//}
	
	if(isOfType(currentObject, "div")){
		if(currentObject.id == "dot_divLayerPanel" || currentObject.id == "fileBrowserWindow"){
		 	currentMenu = null;
		 }
	  	 else if(currentObject.id == "wrapper" ){
		 	//currentMenu = $('htmlmenu');
			currentMenu = null;
		 }
	  	 else if(currentObject.attributes.getNamedItem('id').value != "header" && 
			currentObject.attributes.getNamedItem('id').value != "footer" && 
			currentObject.attributes.getNamedItem('id').value != "divAttributes" && 
			currentObject.attributes.getNamedItem('id').value != "appMenu")
		 {
				currentMenu = $('divmenu');
		 }
	}
	else if (isOfType(currentObject, "html") || isOfType(currentObject, "body")) {
		currentMenu = $('htmlmenu');
  	}
	else if(isOfType(currentObject, "ul")){
		currentMenu = null;
	}	
	else if (isOfType(currentObject, "a") || isOfType(currentObject, "anchor")) {
	  	if(currentObject.id !== null && currentObject.id !== "" ){
			currentMenu = $('linkmenu');
		}else{
			currentMenu = null;
		}
	}
	else if(isOfType(currentObject, "input")){
		currentMenu = null;
	}
	else if (isOfType(currentObject, "img")) 
	{
	  	if(currentObject.id !== null && currentObject.id !== "" ){
			currentMenu = $('imgmenu');
		}else{
			currentMenu = null;
		}
  	}
	else if (isOfType(currentObject, "span")) {
  		if(currentObject.id !== null && currentObject.id !== "" ){
			currentMenu = $('txtmenu');
		}else{
			currentMenu = null;
		}
	}
	else{
	  	currentMenu = null;
	}
	
	if(currentMenu){
		Util.placeAtClick(currentMenu,e, true);
		currentMenu.show();
	}
	return false ; 
}

function displayMenu(e) {
	window.currentObject = e.target;
	setGlobalEvent(e);
	
	//if(currentObject.id && currentObject.id != "wrapper"){
		selectElement(currentObject.id);
	//}

  if (e.target instanceof HTMLDivElement) 
  { 
  	 if(e.target.attributes.getNamedItem('id').value == "dot_divLayerPanel" ||
		e.target.attributes.getNamedItem('id').value == "fileBrowserWindow"){
	 	currentMenu = null;
	 }
  	 else if(e.target.attributes.getNamedItem('id').value == "wrapper" ){
	 	currentMenu = $('htmlmenu');
	 }
  	 else if(e.target.attributes.getNamedItem('id').value != "wrapper" &&
		e.target.attributes.getNamedItem('id').value != "header" &&
		e.target.attributes.getNamedItem('id').value != "footer"&&
		e.target.attributes.getNamedItem('id').value != "divAttributes"&&
		e.target.attributes.getNamedItem('id').value != "appMenu")
	 {
			currentMenu = $('divmenu');
	 }
  } else if (e.target instanceof HTMLHtmlElement || e.target instanceof HTMLBodyElement) {
  	  currentMenu = $('htmlmenu');
  }	 
  else if (e.target instanceof HTMLImageElement) 
  {
  	if(e.target.id !== null && e.target.id !== "" ){
		currentMenu = $('imgmenu');
	}else{
		currentMenu = null;
	}
  }
  else if(e.target instanceof HTMLUListElement){
		currentMenu = null;
  }	
  else if (e.target instanceof HTMLAnchorElement) 
  {
  	if(e.target.id !== null && e.target.id !== "" ){
		currentMenu = $('linkmenu');
	}else{
		currentMenu = null;
	}
  } else if(e.target instanceof HTMLInputElement){
  		currentMenu = null;
  }
  else if (e.target instanceof HTMLSpanElement) 
  {
  		if(e.target.id !== null && e.target.id !== "" ){
			currentMenu = $('txtmenu');
		}else{
			currentMenu = null;
		}
  }  else{
  	currentMenu = null;
  }
  
  if(currentMenu){
  	Util.placeAtClick(currentMenu,e, true);
  	currentMenu.show();
  }
  
  return false ; 
}


/* **********************************************
 * Add / Delete Component Handlers
 * **********************************************/
 function addFlashObj(swf, wasDropped) {
	var o = document.createElement('object');
	o.setAttribute('data', swf);
	o.setAttribute('width', '400');
	o.setAttribute('height', '400');
	
	var p = document.createElement('param');
	p.setAttribute('name', 'movie');
	p.setAttribute('value', swf);
	o.appendChild(p);
	
	p = document.createElement('param');
	p.setAttribute('name', 'quality');
	p.setAttribute('value', 'high');
	o.appendChild(p);
	
	var embed = document.createElement('embed');
	embed.setAttribute('src',Util.removePath(swf,false));
	embed.setAttribute('quality', 'high');
	embed.setAttribute('pluginspage', 'http://www.macromedia.com/go/getflashplayer');
	embed.setAttribute('type', 'application/x-shockwave-flash');
	//o.appendChild(embed);
	
	var bgBox = addNewBox(currentObject, 0, 0, "", false, false, wasDropped);
	bgBox.appendChild(o);
}

function addBox(e,kind,toplevel){
	if (currentObject && isOfType(currentObject,'div') && currentObject.id != "wrapper") {
		toplevel = false;
	}else{
		toplevel = true;
	}
   // every button click hides the current menu
   Util.hideMenu();

   newDiv = document.createElement('div');

   // give it a unique id
   newDivId = document.createAttribute('id');
   divCounter = divCounter + 1;
   newDivId.value = 'div'+divCounter;
   newDiv.setAttributeNode(newDivId);

   newDiv.setAttribute('kind',kind);
   newDiv.setAttribute('name', 'Item '+ divCounter);
   newDiv.setAttribute('action','');
   //newDiv.setAttribute('class','extResizable');

   /*
	//for resize feature
	//newDiv.setAttribute('onmousedown','getDivPosition(event);');
	// onclick action
	//	newDiv.setAttribute('onClick','divClick(event);')
	*/
	
   // remember its level
   newDivLevel = document.createAttribute('level');
   newDivLevel.value = (toplevel) ? 0 : parseInt(currentObject.attributes.getNamedItem('level').value,10) + 1;
   newDiv.setAttributeNode(newDivLevel);

   if (toplevel) {
		newDiv.setAttribute('style','position:absolute; top:0px; left:0px; z-index:3;');
   } else {
		newDiv.setAttribute('style','position:absolute; top:0px; left:0px; z-index:3;');
   }
   
   // specify the div's size and color
   var color = (newDivLevel.value > 4) ? "#3A75B4" : levelColors[newDivLevel.value];

	var size = (newDivLevel.value > 4) ? 50 : (6-newDivLevel.value)*50;
	newDiv.style.backgroundColor = color;
	newDiv.style.width = size+"px";
	newDiv.style.height = size+"px";
	newDiv.style.zIndex = 5;
	if (toplevel) {
		$('wrapper').appendChild(newDiv);
		Util.placeAtClick(newDiv, null, toplevel);
	}else{
		currentObject.appendChild(newDiv);
		Util.placeAtClick(newDiv, null,toplevel);
	}
	
	addDivToDivPanel(newDivId.value);
	
	if(currentObject && currentObject.style){
		currentObject.style.cursor = "default";
	}
	window.currentObject = newDiv;
	activateElement(currentObject);
}

function addDivToDivPanel(divId){
	var tableObj = $("dot_divLayerPanel_table");

	var newRow = tableObj.insertRow(-1);
	newRow.id = "row"+divId;
	var newCol1  = newRow.insertCell(0);
	var newCol2  = newRow.insertCell(1);

	//style
	newCol1.className = "panelClm";
	newCol2.className = "panelClm";
	
	//newCol1.width = "16px";
	
	var newBtnID = "btn"+divId;
	newCol1.innerHTML = "<form><input type='button' class='eyeBtn' id='"+newBtnID+"' onclick='Util.toggleEyeButton(\""+divId+"\",true);'></form>";
	newCol2.innerHTML = ""+divId;
	
	//onclick select div
	newCol2.setAttribute('onClick','selectElement("'+divId+'");');
	
	var divObj = $(divId);
	if(divObj){
		var level = parseInt(divObj.getAttribute("level"),10);
		var dotText = ":";
		for(var i=0;i<level;i++){
			dotText += ".";
		}
		newCol2.innerHTML = dotText+divId;
	}
	
	/*var leftMargin = level*4;
	newCol2.setAttribute("style","padding-left:"+leftMargin+"px;"); */
}

function deleteBox(e,object){
	Util.hideMenu();
	hideProperties();
	if(isOfType(currentObject,'img')){
		/* delete image and the hidden box */
		currentObject.parentNode.parentNode.removeChild(currentObject.parentNode);
	}else if(isOfType(currentObject,'div')){
		if(currentObject.id && currentObject.id != "wrapper"){
			currentObject.parentNode.removeChild(currentObject);
			/* remove from div list panel */
			deleteDivFromPanel(currentObject);
		}		
	}else if(isOfType(currentObject,'span')){
		/* delete text and the box */
		currentObject.parentNode.parentNode.removeChild(currentObject.parentNode);
	}else{
		currentObject.parentNode.removeChild(currentObject);
		//remove from div list panel
		deleteDivFromPanel(currentObject);
	}
	Util.hideMenu();
	clearCSSPanel();
	currentObject = null;
}

function deleteDivFromPanel(div){
	if(isOfType(div,'div'))
	{
		var childNodesList = div.childNodes;
		for(var i = 0; i < childNodesList.length; i++){
			deleteDivFromPanel(childNodesList[i]);
		}
		var delID = "row"+div.id;
		var row = $(delID);
		try {
			if(row){
				row.parentNode.deleteRow(row.rowIndex);
			}
		}
		catch (e) {
			if(row){
				row.parentNode.deleteRow(-1);
			}
		}
	}
}

function addImage(imgLocation,wasDropped){
	var newImg = document.createElement('img');
	imgLocation = Util.stringReplaceAll(imgLocation, "\\", "/");
	if(imgLocation.indexOf("file://") == -1) //if file:// not found
	{
		newImg.setAttribute('src','file://'+imgLocation);
	}else{
		newImg.setAttribute('src',imgLocation);
	}
	
	newImg.setAttribute('alt','Image');
	newImg.setAttribute('border','0');

    imgCounter = imgCounter + 1;
    newImg.setAttribute('id','img'+imgCounter);

	//alert("Image Added");
	var iH = newImg.height;
	var iW = newImg.width;
	
	if(wasDropped){
		currentObject = $("wrapper");
	}
	
	var bgBox = addNewBox(currentObject, 0, 0, "NO_RESIZE", false, false, wasDropped);
	/*Hack to hide and update its dimension*/
	//bgBox.style.display = "none";

	bgBox.appendChild(newImg);
	return bgBox;
}

editTxtID = "";
editor = null;

function getTxtValFromForm(form) {
	editor.dispose();
	var formElements = form.elements;
	$(editTxtID).innerHTML = formElements[0].value;
	editTxtID ="";
}
 
function handleEditText(){
	editTxtID = currentObject.id;
	editor = new Ajax.InPlaceEditor(currentObject,'',
				{	rows:15,
					cols:40,
					submitOnBlur:true,
					okButton:false,
					cancelLink:false,
					externalControl: '',
					callback: function(form) { getTxtValFromForm(form); }
				});
	editor.enterEditMode('click');
}

function addText(textValue){
	newSpan = document.createElement('span');
	newSpan.innerHTML = textValue;
	newSpan.setAttribute('class','');
	
	//STYLE PROPERITES
	newSpan.style.fontFamily = 'arial';
	newSpan.style.color = '#000000';
	newSpan.style.fontSize = '12px';
	
    spanCounter = spanCounter + 1;
    newSpan.setAttribute('id','span'+spanCounter);
	var bgBox = addNewBox(currentObject, 120, 120, "", true, false,false);
	bgBox.appendChild(newSpan);
}

function addNewBox(parentBox, height, width, dragNDropFeatures, colorNeeded, relativePos, wasDropped){
	if(parentBox === null || isOfType(parentBox,'html') || (isOfType(parentBox,'div') && parentBox.id == "wrapper") ){
		toplevel = true; 
	}else{
		toplevel = false; 
	}
	
	var newDiv = document.createElement('div');
	
	divCounter = divCounter + 1;
	newDiv.setAttribute('id','div'+divCounter);
	newDiv.setAttribute('name','Item '+ divCounter);   
//	newDiv.setAttribute('onClick','divClick(event);');
	newDiv.setAttribute('action','');
	if(relativePos){
		newDiv.setAttribute('style', 'position:relative; top:25px; left:25px; z-index:3;');
	}else{
		newDiv.setAttribute('style', 'position:absolute; top:25px; left:25px; z-index:3;');
	}
	
	newDivLevel = document.createAttribute('level');
	if (toplevel) {
	 newDivLevel.value = 0;
	} else {
		if(parentBox.attributes.getNamedItem('level')){
			newDivLevel.value = parseInt(parentBox.attributes.getNamedItem('level').value,10) + 1;
		}
	}
	newDiv.setAttributeNode(newDivLevel);

	if(colorNeeded)
	{
		// specify the div's size and color
		var color = (newDivLevel.value > 4) ? "white" : levelColors[newDivLevel.value];
		newDiv.style.backgroundColor = color;
	}
	
	newDiv.style.width = width+"px";
	newDiv.style.height = height+"px";
  
  	if (toplevel) {
		$('wrapper').appendChild(newDiv);
   	} else {
     	parentBox.appendChild(newDiv);
   	}
	
	if(!wasDropped) { Util.placeAtClick(newDiv, null,toplevel); }
  
	if(dragNDropFeatures !== ""){
	  	if(dragNDropFeatures == "NO_RESIZE"){
	    	//newDiv.setAttribute('onmousedown','');
		}
	}else {
	    //newDiv.setAttribute('onmousedown','getDivPosition(event);');
	}

  return newDiv;
}

function addLink(elementName,altText,urlName,targetText,upImgLink,overImgLink,actionText,menuContainerDiv){
		var newAnchor = document.createElement('a');
		if(actionText === "")
		{
			newAnchor.setAttribute('href',urlName);
			newAnchor.setAttribute('target',targetText);
		}else{
			newAnchor.setAttribute('href','javascript:;');
		}
		
		
		//onClick
		var onClickVal = "MM_nbGroup('down','group1','" + elementName + "','',1)";
		/*if(actionText != ""){
			onClickVal = onClickVal + "; " + actionText;
		}*/
		newAnchor.setAttribute('onClick',onClickVal);
		
		newAnchor.setAttribute('onMouseDown',actionText);
		
		
		//onMouseOver
		var onMouseOverVal = "MM_nbGroup('over','" + elementName + "','file://" + Util.removeColon( overImgLink ) + "','',1)" ;	
		newAnchor.setAttribute('onMouseOver',onMouseOverVal);
		
		//onMouseOut
		var onMouseOutVal = "MM_nbGroup('out')";
		newAnchor.setAttribute('onMouseOut',onMouseOutVal);
		
		// adding the image
		var newImg = document.createElement('img');
		newImg.setAttribute('border','0');
		newImg.setAttribute('onload','');
		newImg.setAttribute('alt',altText);
		newImg.setAttribute('src',"file://" + upImgLink);
		newImg.setAttribute('name',elementName);
		//divCounter = divCounter + 1;
		//newImg.setAttribute('id','img'+divCounter);
		
		newAnchor.appendChild(newImg);
		// //////////////////////////////////////////
		
		//alert("Menu added");
		//var bgDiv = addNewBox(menuContainerDiv, newImg.height, newImg.width, "NO_RESIZE", false, false); //creating a new box for the link
		var bgDiv = addNewBox(menuContainerDiv, 30, 50, "NO_RESIZE",false,true,false); //creating a new box for the link
		bgDiv.appendChild(newAnchor); //add link to the box		
		
		/*  //OVER IMAGE
		<a 
			href="http://www.google.com" 
			target="_top" 
			onClick="MM_nbGroup('down','group1','Google','',1)" 
			onMouseOver="MM_nbGroup('over','Google','file:///D|/Shiva/other_projects/SELF/ver6/img/minitick.gif','',1)" 
			onMouseOut="MM_nbGroup('out')">
		
			//UP IMAGE
			<img 
				name="Google" 
				src="file:///D|/Shiva/other_projects/SELF/ver6/img/minirss.gif" 
				border="0" 
				alt="Google" 
				onLoad="">
		</a>
		*/	
}

function addButton(e,kind){
	Util.hideMenu();
	
	//form
	newForm = document.createElement('form');
	
	newFormAction = document.createAttribute('action');
   	newFormAction.value = 'javascript:;';
   	newForm.setAttributeNode(newFormAction);
	
	//button
	newInput = document.createElement('input');

	// give it a unique id
   newInputID = document.createAttribute('id');
   inputCounter = inputCounter + 1;
   newInputID.value = 'btn'+inputCounter;
   newInput.setAttributeNode(newInputID);
   
	newInputType = document.createAttribute('type');
   	newInputType.value = 'submit';
   	newInput.setAttributeNode(newInputType);
   
	newInputValue = document.createAttribute('value');
	if(kind == 'addBox'){
		newInputValue.value = 'Add a box';
	}
	else if(kind == 'deleteBox'){
		newInputValue.value = 'Delete box';
	}
   	
   	newInput.setAttributeNode(newInputValue);
	
	newInputOnMouseDown = document.createAttribute('onMouseDown');
   	//newInputOnMouseDown.value = 'Util.toggleDiv(\'struct\');';
	if(kind == 'addBox'){
		newInputOnMouseDown.value = 'addBox(event,\'box\',false);';
	}
	else if(kind == 'deleteBox'){
		newInputOnMouseDown.value = 'deleteBox(event,this);';
	}
   	newInput.setAttributeNode(newInputOnMouseDown);
	
	newForm.appendChild(newInput);
	currentObject.appendChild(newForm);
	
	//<form action="javascript:;"><input onMouseDown="Util.toggleDiv('struct');" type="button" value="click here"></form>
}


/* **********************************************
 * Adding / Updating Javascript Handlers
 * **********************************************/
function addJSToJSPanel(location){
	var fName = Util.removePath(location,false);
	var tableObj = $("dot_customJSPanel_table");

	var newRow = tableObj.insertRow(-1);
	newRow.id = "row"+fName;
	
	var newCol1  = newRow.insertCell(0);
	newCol1.className = "panelClm";
	
	var newAnchor = document.createElement('a');
	newAnchor.innerHTML = fName;
	newAnchor.href="javascript:;";
	newAnchor.setAttribute("onClick","updateJSEditAreaWithValue('"+fName+"');Util.showDialog('jsEditArea', 'Edit Javascript', 600);");
	newCol1.appendChild(newAnchor);
}

function addJavascript(location){
	var javaScriptTextFromFile = Util.readFromFile(location);
	var heads = document.getElementsByTagName('head');
	var headText = heads[0].innerHTML;
	headText += "\n<script type=\"text\/javascript\" id=\""+Util.removePath(location,false)+"\">\n" + javaScriptTextFromFile + "\n</script>";
	heads[0].innerHTML = headText;
	
	addJSToJSPanel(location);
	Util.showDiv('dot_customJSPanel');
}

function addEmptyJSScript(){
	var id = $("dot_customJSPanel_JSID").value;
	if($(id) !== null){
		alert('Duplicate name found.  Please give a unique name.');
		return;
	}
	var heads = document.getElementsByTagName('head');
	var headText = heads[0].innerHTML;
	
	headText += "<script type=\"text\/javascript\" id=\""+id+"\"></script>";
	heads[0].innerHTML = headText;
	
	$("dot_customJSPanel_JSID").value = "";
	addJSToJSPanel(id);
	Util.showDiv('dot_customJSPanel');
	
}

var jsID = "";
function updateJSEditAreaWithValue(location){
	//$("jsEditArea.form1.textValue").innerHTML = Util.readFromFile(location);
	$("jsEditArea.form1.textValue").innerHTML = $(location).innerHTML;
	jsID = location;
}

function updateJSFromEditArea(val){
	$(jsID).innerHTML = val;
	jsID = "";
	$("jsEditArea.form1.textValue").innerHTML = "";
}

function deleteJS(){
	Modalbox.hide('jsEditArea');
	$(jsID).remove();
	$("row"+jsID).remove();
	jsID = "";
}

/* **********************************************
 * Copy and Paste Handlers
 * **********************************************/
function copyElement(){
	Util.hideMenu();
	globalCopyObj = currentObject;
	//$("div_paste_option").show();
}

function pasteElement(){
	Util.hideMenu();
	var newObj = globalCopyObj.cloneNode(true);
	currentObject.appendChild(newObj);
	globalCopyObj = null;
	//$("div_paste_option").hide();
	updateElementIDsAndDraggable(newObj);
	activateElement(newObj);
	Util.placeAtClick(newObj, null, false);
}

function updateElementIDsAndDraggable(element){
	if(isOfType(element,'div')||isOfType(element,'a')||isOfType(element,'img')||isOfType(element,'span'))
	{
		var idValue = element.id;
		if(idValue && idValue !== "" && idValue.length>0)
		{
			var newIDVal = "";
			if(isOfType(element,'div')){
				newIDVal = "div"+ (++divCounter);
				if(element.style.width != "0px" && element.style.height != "0px"){
					addDivToDivPanel(newIDVal);
				}
			}else if(isOfType(element,'a')){
				newIDVal = "anchor"+ (++anchorCounter);
			}else if(isOfType(element,'img')){
				newIDVal = "img"+ (++imgCounter);
			}else if(isOfType(element,'span')){
				newIDVal = "span"+ (++spanCounter);
			}
			
			element.setAttribute("id",newIDVal);			
		}
		
		/* UPDATING CHILDREN */
		var elementList = element.childNodes;
		var count = 0;
		while(count < elementList.length)
		{
			var childElement = elementList.item(count);
			updateElementIDsAndDraggable(childElement);
			count++;
		}
	}	
	return;
}

/* **********************************************
 * Selecting elements Handlers
 * **********************************************/
var dottedDiv = null;
function selectItem(e){
	if(dottedDiv){
		dottedDiv.parentNode.removeChild(dottedDiv);
	}
	
	dottedDiv = currentObject.cloneNode(false);
	
	if(isOfType(currentObject.parentNode ,'div') &&	currentObject.parentNode.id != "wrapper")
	{
		var parentX = Util.getAncestorLeft(currentObject.parentNode);
		var parentY = Util.getAncestorTop(currentObject.parentNode);
		var existingX = parseInt(dottedDiv.style.left.replace("px",""),10);
		var existingY = parseInt(dottedDiv.style.top.replace("px",""),10);
		
		dottedDiv.style.left = (existingX + parentX) +"px";
		dottedDiv.style.top = (existingY + parentY) + "px";
	}
	dottedDiv.setAttribute('level','-1');
	dottedDiv.style.backgroundColor = "transparent";
	dottedDiv.style.border = "1px dotted #000000";
	$("wrapper").appendChild(dottedDiv);
}

var objToAnimate = null;
var blinkingTimeCounter = 0;
function divClick(e){
	//if(key == 'shift'){
	
		if(e.target === null){
			window.currentObject = e;
		}else{
			window.currentObject = e.target;
		}
		/* Highlighting the DIV id in the DIV Panel */
		resetBGInDivPanel();
		highlightDivInDivPanel(currentObject.id,true);	
		/* ************************************* */
		
		var startcol = currentObject.style.backgroundColor;
		var hexCol = "#"+this.RGB2HTML(startcol);
		//new Effect.Highlight(currentObject, {startcolor: "#ffffff", restorecolor: hexCol});
		//new Effect.Pulsate(currentObject,{duration:1,pulses:2} );
		
		//highlightElement();
		
		if (isOfType(currentObject,'html')){ // page
			attributesEdit('page');
		}else if(isOfType(currentObject,'div'))
		{
			attributesEdit('div');
		}
		else if (isOfType(currentObject,'img')){ //image
			attributesEdit('image');
		}else if (isOfType(currentObject,'span')){ // text
			attributesEdit('text');
		}
		
		if(isOfType(currentObject,'div')){
			updateCSSPanel();
		}
	//}
}

function highlightElement(){
	var overlayDiv = currentObject.cloneNode(false);
	
	if(isOfType(currentObject.parentNode,'div') &&	currentObject.parentNode.id != "wrapper")
	{
		var parentX = Util.getAncestorLeft(currentObject.parentNode);
		var parentY = Util.getAncestorTop(currentObject.parentNode);
		var existingX = parseInt(overlayDiv.style.left.replace("px",""),10);
		var existingY = parseInt(overlayDiv.style.top.replace("px",""),10);
		
		overlayDiv.style.left = (existingX + parentX) +"px";
		overlayDiv.style.top = (existingY + parentY) + "px";
	}
	
	overlayDiv.style.backgroundColor = "transparent";
	overlayDiv.style.border = "3px solid #000000";
	$("wrapper").appendChild(overlayDiv);
	objToAnimate = overlayDiv;
	var pulsateEffect = new Effect.Pulsate(objToAnimate, {duration:2});

	setTimeout('removeHighlight()',2000);
	//borderchange1(); //animating
	return;
}

function removeHighlight(){
	objToAnimate.parentNode.removeChild(objToAnimate);
}

function selectElement(divID){
	var obj =  $(divID);
	//Position.absolutize(obj);
	//Position.relativize(obj);
	
	if(!isOfType(obj,"span")){
		var eff = new Effect.Highlight(obj,{pulses:2});
	}
	
	/* Highlighting the DIV id in the DIV Panel */
	resetBGInDivPanel();
	highlightDivInDivPanel(currentObject.id,true);	
	/* ************************************* */

	/* Showing properties and updating css panel */
	if (isOfType(currentObject,'html')){ /* page */
		attributesEdit('page');
	}else if(isOfType(currentObject,'div')){ /* div */
		if(currentObject.id == "wrapper"){
			attributesEdit('page');
		}else{
			attributesEdit('div');
		}
		updateCSSPanel();
	}else if (isOfType(currentObject,'img')){ /* image */
		attributesEdit('image');
	}else if (isOfType(currentObject,'span')){ /* span */
		attributesEdit('text');
		handleEditText();
	}
}

function resetBGInDivPanel(){
	var myTDElements = $("dot_divLayerPanel_table").getElementsByTagName("td");
	
	for(var i=0; i<myTDElements.length; i++){
		var tdElement = myTDElements[i];
		tdElement.style.backgroundColor ="";
	}
}

function highlightDivInDivPanel(divID, addColor){	
	var rowObj = $("row"+divID);
	if(rowObj){
		var cNodes = rowObj.childNodes;
		if(cNodes.length > 1){
			var col = cNodes[1];
			if(col){
				if(addColor){
					col.style.backgroundColor="#ff9900";
				}
				else{
					col.style.backgroundColor="";
				}
			}
		}
	}
}



function borderchange1() {
	//reduceDimensionOfDIV();
	objToAnimate.className="withBorder";
	setTimeout("borderchange2()",100);
}

function borderchange2() {
	//resetDimensionOfDIV();
	objToAnimate.className="";
	
	if(blinkingTimeCounter < 2){
		blinkingTimeCounter++;	
		setTimeout("borderchange1()",100);
	}else{
		blinkingTimeCounter = 0;
	}
}

/* **********************************************
 * Dialog Box Handlers
 * **********************************************/
 function getImageSrc(){
	var imgLocationInput = $("dialog1.form1.imgLocation");
	if(imgLocationInput.value !== "")
	{
		Modalbox.hide('dialog1');
		globalBgBox = addImage(imgLocationInput.value, false);
	}
}

function getTextValue(){
	var textValueInput = $("dialog2.form1.textValue");
	if(textValueInput.value !== "")
	{
		Modalbox.hide('dialog2');
		addText(textValueInput.value);
	}
}

function getJSValue(){
	var jsValueInputVal = $("jsEditArea.form1.textValue").value;
	if(jsValueInputVal !== "")
	{
		Modalbox.hide('jsEditArea');
		updateJSFromEditArea(jsValueInputVal);
	}
}

function getMenuValue(){
	
	/* ****************************************/
	Modalbox.hide('dialog3');
	var i = 0;
	var preloadImgList = "";
	var totalLinks = parseInt($("dialog3.form1.noOfLinks").value,10);
	/* ****************************************
		height and width of the menu container */
	var boxHeight = Util.stringReplaceAll(currentObject.style.height,"px","");
	var boxWidth = Util.stringReplaceAll(currentObject.style.width,"px","");
	
	if(boxHeight === 0 || boxWidth === 0){
		boxHeight = boxWidth = 300;
	}
	
	var menuContainerDiv = addNewBox(currentObject, boxHeight-20, 300, "", true, false,false );
	/* *****************************************/
	
	while(i < totalLinks)
	{
		var elementName = "elementName"+i;
		var altText = "altText" + i;
		var urlName = "url"+i;
		var targetText = "target" + i;
		var upImgLink = "uImg" + i;
		var overImgLink = "oImg" + i;
		var actionText = "actionText" + i;
		
		addLink($(elementName).value,
						$(altText).value,
						$(urlName).value,
						$(targetText).value,
						$(upImgLink).value,
						$(overImgLink).value,
						$(actionText).value,
						menuContainerDiv);

		// pre loading images for roll over
		if(preloadImgList !== ""){
			preloadImgList += ",";
		}
		preloadImgList = preloadImgList + "'file://" + $(upImgLink).value + "','file://" + $(overImgLink).value + "'";

		//add a <br> after the link
		menuContainerDiv.appendChild(document.createElement('br'));
		i = i+1;
		if(i === 0){
			 // HACK TO STORE THE NEWLY ADDED INPUTS; Reason: The newly added inputs disappear from the 2nd access to the table
			$("linkListTable.hidden").innerHTML = $("linkListTable").innerHTML;	
		}
	}
	var bodyTag = $('dotBody');
	bodyTag.setAttribute("onLoad", bodyTag.getAttribute("onLoad") + "MM_preloadImages(" + preloadImgList + ");" );		//	onLoad="MM_preloadImages('file:///D|/Shiva/other_projects/SELF/ver6/img/minitick.gif','siva3.jpg','siva4.jpg','siva.png')"				

	//clearing the hidden temporary table
	$("linkListTable.hidden").innerHTML = "";
}

var linkListCounter = 0;
function addNewLinkToList(){
	Modalbox.resize(0,20);
	linkListCounter = linkListCounter + 1;
	var tableObj = $("linkListTable");
	
	var newRow = tableObj.insertRow(linkListCounter+2);
	
	var newCol1  = newRow.insertCell(0);
	var newCol2  = newRow.insertCell(1);
	var newCol3  = newRow.insertCell(2);
	var newCol4  = newRow.insertCell(3);
	var newCol5  = newRow.insertCell(4);
	var newCol6  = newRow.insertCell(5);
	var newCol7  = newRow.insertCell(6);
	
	newInput1 = document.createElement('input');
	newInput1.setAttribute('type','text');
	newInput1.setAttribute('width','10');
	newInput1.setAttribute('name','elementName'+linkListCounter);
	newInput1.setAttribute('id','elementName'+linkListCounter);
	
	newInput2 = document.createElement('input');
	newInput2.setAttribute('type','text');
	newInput2.setAttribute('width','10');
	newInput2.setAttribute('name','altText'+linkListCounter);
	newInput2.setAttribute('id','altText'+linkListCounter);
	
	newInput3 = document.createElement('input');
	newInput3.setAttribute('type','text');
	newInput3.setAttribute('width','10');
	newInput3.setAttribute('name','url'+linkListCounter);
	newInput3.setAttribute('id','url'+linkListCounter);
	newInput3.setAttribute('onkeydown','Util.enableDisableAction('+linkListCounter+', "url", "actionText");');
	
	newSelect = document.createElement('select');
	newSelect.setAttribute('name','target'+linkListCounter);
	newSelect.setAttribute('id','target'+linkListCounter);
	newSelect.innerHTML = '<option value="_blank" selected="selected">_blank</option><option value="_parent">_parent</option><option value="_self">_self</option><option value="_top">_top</option>';
	
	newInput5 = document.createElement('input');
	newInput5.setAttribute('type','file');
	newInput5.setAttribute('width','10');
	newInput5.setAttribute('name','uImg'+linkListCounter);
	newInput5.setAttribute('id','uImg'+linkListCounter);
	
	newInput6 = document.createElement('input');
	newInput6.setAttribute('type','file');
	newInput6.setAttribute('width','10');
	newInput6.setAttribute('name','oImg'+linkListCounter);
	newInput6.setAttribute('id','oImg'+linkListCounter);
	
	newInput7 = document.createElement('input');
	newInput7.setAttribute('type','text');
	newInput7.setAttribute('width','50');
	newInput7.setAttribute('name','actionText'+linkListCounter);
	newInput7.setAttribute('id','actionText'+linkListCounter);
	newInput7.setAttribute('onkeydown','Util.enableDisableAction('+linkListCounter+', "actionText", "url");');
	
	newCol1.appendChild(newInput1);
	newCol2.appendChild(newInput2);
	newCol3.appendChild(newInput3);
	newCol4.appendChild(newSelect);
	newCol5.appendChild(newInput5);
	newCol6.appendChild(newInput6);
	newCol7.appendChild(newInput7);

	if(linkListCounter > 0)	{
		//enable link
		$('deleteLinkButton').setAttribute('onmousedown','removeLinkFromList()');
	}
	var noOfLinksVal = $("dialog3.form1.noOfLinks").value;
	$("dialog3.form1.noOfLinks").value = parseInt(noOfLinksVal,10)+1;
}

function removeLinkFromList(){
	Modalbox.resize(0,-20);
	var tableObj = $("linkListTable");
	tableObj.deleteRow(linkListCounter+2);	
	linkListCounter = linkListCounter - 1;
	
	if(linkListCounter === 0){
		//disable link
		$('deleteLinkButton').setAttribute('onmousedown','');
	}
}


/* **********************************************
 * FILE SAVE / EXPORT Handlers
 * **********************************************/

 /*function getDIVList(div)
{
	var listText = "";
	var divList = div.childNodes;
	var count = 0;
	while(count < divList.length)
	{
		var divElement = divList.item(count);
		if(divElement instanceof HTMLDivElement)
		{
			var idValue = divElement.id;
			if(idValue != "header" && idValue != "footer")
			{
				if(listText != ""){
					listText += ',';
				}
				listText += '\"' + idValue + '\"';
				
				//adding divs of the children div
				var subListText = getDIVList(divElement);
				if(subListText != ""){
					listText += ',' + subListText;	
				}
			}
		}
		count++;
	}
	return listText;
}*/

function resetColorSectors(){
	//$('colorSelector').innerHTML = "<input type=\"text\" class=\"color\" value=\"#FFFF00\">";

	var inputNodes = document.getElementsByTagName('input');
	for (var i = 0; i < inputNodes.length; i++)
	{
		var node = inputNodes[i];
		//if(!node.descendantOf('colorSelector')) continue;
		if (node.className != 'color'){
			continue;
		}
		var divToRemove = node.parentNode;
		//alert(divToRemove)
		divToRemove.parentNode.replaceChild(node,divToRemove);
	}
}
function saveHTML() {
	//removing color panel before saving
	resetColorSectors();
	
	//hiding the properties panel before saving
	hideProperties();
	
	var htmls = document.getElementsByTagName("html");
	htmlCode = "<html>" + htmls[0].innerHTML + "</html>";
	
	window.frames.SaveFrame.document.open("text/html", "replace");
	window.frames.SaveFrame.document.write(htmlCode);
	window.frames.SaveFrame.document.close();
	window.frames.SaveFrame.focus();

	var fName = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1); 

	// Get page names
	var path_html_draft_page = Util.getHome();
   	HTML_draft_pageNameOld = Util.removePath(path_html_draft_page, false);
	HTML_pageName = "";
	if(fName.toUpperCase() != "ASALTA.HTML"){
		HTML_pageName = fName;
	}

    HTML_pageName = Util.clearText(HTML_pageName);
    if (HTML_pageName === null || HTML_pageName === "") {
        HTML_pageName = "no_name.html";
    }
    //if (HTML_pageName == "filename.html") {
    while(HTML_pageName == "no_name.html" || HTML_pageName.toUpperCase() == "ASALTA.HTML") {
        HTML_pageName = prompt("Enter the name of the HTML page:", "filename.html");
        HTML_pageName = Util.clearText(HTML_pageName);
        if (HTML_pageName === null || HTML_pageName === "") {
			//if cancel or empty string return
			return;
        }
    }
    HTML_pageName = HTML_pageName.replace("\.html", "");
    HTML_pageName = Util.clearText(HTML_pageName);
    if (HTML_pageName === null || HTML_pageName === "") {
        HTML_pageName = "no_name.html";
    }
	
	HTML_pageName = HTML_pageName + ".html";

	var path = Util.stringReplaceAll(path_html_draft_page, HTML_draft_pageNameOld, HTML_pageName);
	/*path = Util.stringReplaceAll(path, "/", "\\");
	path = Util.stringReplaceAll(path, "%20", " ");
	path = path.replace("_draft", "");*/
	
	// save and redirect
	Util.writeToFile(path, htmlCode);
	Util.redirectWindow( "file://" + path );
}

function getDivHtmlCode(div){
	var divHtmlCode = "";
	var divsList = div.childNodes;
	var count = 0;
	while(count < divsList.length)
	{
		var retDiv = divsList.item(count);
		
		if(isOfType(retDiv,'div'))
		{
			var idValue = retDiv.id;
			if(idValue != "header" && idValue != "footer")
			{
				divHtmlCode += '\n<div ';
				//adding the attributes of the div to the code
				var retDivAttributes=retDiv.attributes;
				for (var i = 0; i < retDivAttributes.length; i++) {
					//removing the cursor value
					retDivAttributes[i].value = Util.stringReplaceAll(retDivAttributes[i].value, "cursor: move;", "");
					
					divHtmlCode += retDivAttributes[i].name + "=\""+ retDivAttributes[i].value + "\" ";
				}
				divHtmlCode += ' >\n';
				//divHtmlCode += retDiv.innerHTML;
				divHtmlCode += Util.stringReplaceAll(retDiv.innerHTML, "cursor: move;", "");
				divHtmlCode  += '\n</div>';
			}
		}
		count++;
	}
	return divHtmlCode;
}

function generateHTMLCode(){
	var htmlCode = "<html>";
		//HEAD
		htmlCode += "\n<head>" ;
			
			//TITLE
			htmlCode += "\n<title>" + document.title + "</title>";
		
		//ROLL OVER IMAGE SCRIPT
		var homeDir = Util.getHomeDirectory();
		//var rollOverImageScript = Util.readFromFile(document.getElementById("script_rollOverImage").src);
		var rollOverImageScript = Util.readFromFile(homeDir+"js/RolloverImage.js");
		htmlCode += "\n<script type=\"text\/javascript\">\n" + rollOverImageScript + "\n</script>";

		//COMMANDS SCRIPT
		//var cmdScript = Util.readFromFile(document.getElementById("script.dotCommands").src);
		var cmdScript = Util.readFromFile(homeDir+"js/Commands.js");
		htmlCode += "\n<script type=\"text\/javascript\">\n" + cmdScript + "\n</script>";

		htmlCode += "\n</head>";
		
		//BODY
		if(document.body.style){
			htmlCode += "\n<body style=\"background:"+document.body.style.background+"\">";
		}else{
			htmlCode += "\n<body>";
		}
		htmlCode += getDivHtmlCode($("wrapper"));
		htmlCode += "\n</body>";
	htmlCode += "\n</html>";
	
	/* **************************************************
	 *	CHANGING ABSOLUTE TO RELATIVE PATH
	 * **************************************************/
	var hDir = Util.getHomeDirectory();
	var dirTxt = "file://"+hDir;
	htmlCode = Util.stringReplaceAll(htmlCode,dirTxt,"./");
	
	dirTxt = "file:///"+hDir;
	htmlCode = Util.stringReplaceAll(htmlCode,dirTxt,"./");
	
	dirTxt = "file://" + Util.stringReplaceAll(hDir,":","|");
	htmlCode = Util.stringReplaceAll(htmlCode,dirTxt,"./");
	
	/* *************************************************/
	
	return htmlCode;
}

function exportHTML() {
	var htmlCode = generateHTMLCode();
	
	window.frames.SaveFrame.document.open("text/html", "replace");
	window.frames.SaveFrame.document.write(htmlCode);
	window.frames.SaveFrame.document.close();
	window.frames.SaveFrame.focus();

	// Get page names
	var path_html_draft_page = Util.getHome();
    HTML_draft_pageNameOld = Util.removePath(path_html_draft_page, false);
	HTML_pageName = "";

    HTML_pageName = Util.clearText(HTML_pageName);
    if (HTML_pageName === null || HTML_pageName === "") {
        HTML_pageName = "no_name.html";
    }
    if (HTML_pageName == "no_name.html") {
   // while(HTML_pageName == "no_name.html" || HTML_pageName.toUpperCase() == "ASALTA.HTML") {
        HTML_pageName = prompt("Enter the name of the HTML page:", "filename.html");
        HTML_pageName = Util.clearText(HTML_pageName);
        if (HTML_pageName === null || HTML_pageName === "") {
			return;
        }
    }
    HTML_pageName = HTML_pageName.replace("\.html", "");
    HTML_pageName = Util.clearText(HTML_pageName);
    if (HTML_pageName === null || HTML_pageName === "") {
        HTML_pageName = "no_name.html";
    }
	
	HTML_pageName = HTML_pageName + ".html";
		
	var path = Util.stringReplaceAll(path_html_draft_page, HTML_draft_pageNameOld, HTML_pageName);
	/*path = Util.stringReplaceAll(path_draft, "/", "\\");
	path = Util.stringReplaceAll(path_draft, "%20", " ");
	path = path_draft.replace("_draft", "");*/

	// save export version
	Util.writeToFile(path, htmlCode);
}


/* **********************************************
 * CSS PANEL Handlers
 * **********************************************/

function updateCSSPanel(){
	populateCSSTable(currentObject.getAttribute("style"));
	$("cssPanel_addPropertyTable").show();
}

function clearCSSPanel(){
    if($("cssPanel_table") && $("cssPanel_table").fistChild) {
		$("cssPanel_table").fistChild.remove();
        //if(!$("cssPanel_table").empty())        $("cssPanel_table").innerHTML = ""; 
    }
    if($("cssPanel_addPropertyTable")){ $("cssPanel_addPropertyTable").hide(); }
}

function updateCSSValue(property){
	var skipProperty = false;
	var val = $(property+"_val").value.strip();
	var style = currentObject.getAttribute("style");
	var tokens = style.split(";");
	style = "";
	for(var i=0; i<tokens.length; i++)
	{
		var tokens2 = tokens[i].split(":");
		if(tokens2[0].strip() == property.strip()){
			if(val.length === 0){ skipProperty = true; }
			tokens2[1] = val;
		}
		if(!skipProperty){
			style += tokens2[0]+":"+tokens2[1]+";";
		}
		skipProperty = false;		
	}
	currentObject.setAttribute("style",style);
	updateCSSPanel();
}

function populateCSSTable(txt){
	if(txt.cssText){ txt = txt.cssText; }
	var tokens = txt.split(";");
	var tableObj = $("cssPanel_table");
	if(Util.getBrowser().indexOf("NN") != -1){
		tableObj.innerHTML = "";
	}else{
		tableObj.remove();
		
		tableObj = document.createElement('table');
		tableObj.setAttribute('id','cssPanel_table'); 
		tableObj.setAttribute('cellspacing','0'); 
		tableObj.setAttribute('cellpadding','0');
		tableObj.setAttribute('width','152');
		$('cssPanel').appendChild(tableObj);
	}

	for(var i=0; i<tokens.length; i++)
	{
		if(tokens[i].strip().indexOf("toJSONString") != -1){ break; }
		if(tokens[i].strip().length > 0)
		{
			 //for each style element
			var newRow = tableObj.insertRow(i);
			var newCol1 = newRow.insertCell(0);
			var newCol2 = newRow.insertCell(1);
			
			newCol1.className = "cssLeft";
			newCol2.className = "cssRight";
			
			var styleValues = tokens[i].split(":");
			var prop = styleValues[0].strip();
			var val = styleValues[1].strip();
			
			newCol1.innerHTML = prop;
			newCol1.setAttribute("id",prop);
					
			newInput = document.createElement('input');
			newInput.setAttribute("id",prop+"_val");
			newInput.setAttribute('type','text');
			newInput.setAttribute('size','5');
			newInput.setAttribute('class','textClass2');
			newInput.setAttribute('onblur','updateCSSValue("'+prop+'");');
			newInput.setAttribute('value',val);
			
			newCol2.appendChild(newInput);
		}
	} 
}

function addPropertyToCSS(){
	var property = ""+$("cssPanel_Property").value;
	var value = ""+$("cssPanel_Property_Value").value;
	
	var tableObj = $("cssPanel_table");

	if(property.strip() !== "" && value.strip() !== "" )
	{
		var newRow = tableObj.insertRow(0);
		var newCol1 = newRow.insertCell(0);
		var newCol2 = newRow.insertCell(1);
		
		newCol1.className = "cssLeft";
		newCol2.className = "cssRight";
		
		newCol1.innerHTML = property;
		newCol1.setAttribute("id",property);
		
		newInput = document.createElement('input');
		newInput.setAttribute("id",property+"_val");
		newInput.setAttribute('type','text');
		newInput.setAttribute('size','5');
		newInput.setAttribute('class','textClass2');
		newInput.setAttribute('onblur','updateCSSValue("'+property+'");');
		newInput.setAttribute('value',value);
		
		newCol2.appendChild(newInput);
	}
	
	//updating the style value of the object
	var styleTxt = currentObject.getAttribute("style");
	styleTxt += property+":"+value+";";
	currentObject.setAttribute("style",styleTxt);
	
	//clearing the input values
	$("cssPanel_Property").value = "";
	$("cssPanel_Property_Value").value = "";
}

/* ******************************************************
 * 	AUTO SUGGESTION CSS PANEL
 * *****************************************************/
function bindEvents()
{
	var cssPropertiesArray = ["accelerator","azimuth","background","background-attachment","background-color","background-image","background-position","background-position-x","background-position-y","background-repeat","behavior","border","border-bottom","border-bottom-color","border-bottom-style","border-bottom-width","border-collapse","border-color","border-left","border-left-color","border-left-style","border-left-width","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-style","border-top-width","border-width","bottom","caption-side","clear","clip","color","content","counter-increment","counter-reset","cue","cue-after","cue-before","cursor","direction","display","elevation","empty-cells","filter","float","font","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","height","ime-mode","include-source","layer-background-color","layer-background-image","layout-flow","layout-grid","layout-grid-char","layout-grid-char-spacing","layout-grid-line","layout-grid-mode","layout-grid-type","left","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","max-height","max-width","min-height","min-width","-moz-binding","-moz-border-radius","-moz-border-radius-topleft","-moz-border-radius-topright","-moz-border-radius-bottomright","-moz-border-radius-bottomleft","-moz-border-top-colors","-moz-border-right-colors","-moz-border-bottom-colors","-moz-border-left-colors","-moz-opacity","-moz-outline","-moz-outline-color","-moz-outline-style","-moz-outline-width","-moz-user-focus","-moz-user-input","-moz-user-modify","-moz-user-select","orphans","outline","outline-color","outline-style","outline-width","overflow","overflow-X","overflow-Y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","pause","pause-after","pause-before","pitch","pitch-range","play-during","position","quotes","-replace","richness","right","ruby-align","ruby-overhang","ruby-position","-set-link-source","size","speak","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","table-layout","text-align","text-align-last","text-decoration","text-indent","text-justify","text-overflow","text-shadow","text-transform","vtext-autospace","text-kashida-space","text-underline-position","top","unicode-bidi","-use-link-source","vertical-align","visibility","voice-family","volume","white-space","widows","width","word-break","word-spacing","word-wrap","writing-mode","z-index","zoom"];
	var completer = new Autocompleter.Local('cssPanel_Property', 'cssPanelPropertyAutosuggest', cssPropertiesArray, {});
		/*
		var tag = $("cssPanel_Property");
		//If it's a text tag, attach an AutoSuggest object.
		if(tag.type && tag.type.toLowerCase() == "text")
		{
			var cssProperties = new Array("accelerator","azimuth","background","background-attachment","background-color","background-image","background-position","background-position-x","background-position-y","background-repeat","behavior","border","border-bottom","border-bottom-color","border-bottom-style","border-bottom-width","border-collapse","border-color","border-left","border-left-color","border-left-style","border-left-width","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-style","border-top-width","border-width","bottom","caption-side","clear","clip","color","content","counter-increment","counter-reset","cue","cue-after","cue-before","cursor","direction","display","elevation","empty-cells","filter","float","font","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","height","ime-mode","include-source","layer-background-color","layer-background-image","layout-flow","layout-grid","layout-grid-char","layout-grid-char-spacing","layout-grid-line","layout-grid-mode","layout-grid-type","left","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","max-height","max-width","min-height","min-width","-moz-binding","-moz-border-radius","-moz-border-radius-topleft","-moz-border-radius-topright","-moz-border-radius-bottomright","-moz-border-radius-bottomleft","-moz-border-top-colors","-moz-border-right-colors","-moz-border-bottom-colors","-moz-border-left-colors","-moz-opacity","-moz-outline","-moz-outline-color","-moz-outline-style","-moz-outline-width","-moz-user-focus","-moz-user-input","-moz-user-modify","-moz-user-select","orphans","outline","outline-color","outline-style","outline-width","overflow","overflow-X","overflow-Y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","pause","pause-after","pause-before","pitch","pitch-range","play-during","position","quotes","-replace","richness","right","ruby-align","ruby-overhang","ruby-position","-set-link-source","size","speak","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","table-layout","text-align","text-align-last","text-decoration","text-indent","text-justify","text-overflow","text-shadow","text-transform","vtext-autospace","text-kashida-space","text-underline-position","top","unicode-bidi","-use-link-source","vertical-align","visibility","voice-family","volume","white-space","widows","width","word-break","word-spacing","word-wrap","writing-mode","z-index","zoom");
			new AutoSuggest(tag,cssProperties);
		}*/
		
}


/* ******************************************************
 * 	RESIZING Handlers
 * *****************************************************/

// Global variables 
var currentResizableObj = null;
var currentMovableObj = null;
var currentMovableObj1 = null;
var anchorObject;

function copyLinkOfImage(){
	if(isOfType(currentObject,'img')){
		if(currentObject.parentNode && isOfType(currentObject.parentNode,'a')){
			anchorObject = currentObject.parentNode.cloneNode(false);
			currentObject.parentNode.parentNode.replaceChild(currentObject,currentObject.parentNode);
		}
	}
}

function pasteLinkToImage(){
	if(anchorObject && isOfType(currentObject,'img')){
		if(currentObject.parentNode && isOfType(currentObject.parentNode,'a')===false){
			currentObject.parentNode.replaceChild(anchorObject,currentObject);
			anchorObject.appendChild(currentObject);
		}
	}
}

function disableResizable(){
	pasteLinkToImage();
	if(currentObject && currentObject.style){
		//alert("Resetting "+currentObject.id+"'s cursor to default");
		currentObject.style.cursor = "default";
	}
	
	if(currentResizableObj){ // if box is resizable 
		currentResizableObj.destroy();
		currentResizableObj = null;
	}
	if(currentMovableObj){
		
	}
	if(currentMovableObj){ // if box is movable
		currentMovableObj.destroy();
		currentMovableObj = null;
	}
	if(currentMovableObj1){ // if handler is movable
		currentMovableObj1.destroy();
		currentMovableObj1 = null;
	}
	if($('resizeHandle')){
		$('resizeHandle').remove();
	}	
}

function enableResizable(){
	copyLinkOfImage();
	var resizeHandlerDiv = document.createElement('div');
	resizeHandlerDiv.setAttribute('id','resizeHandle');
	resizeHandlerDiv.innerHTML = Util.getResizeSquareIconHTML();
	currentObject.appendChild(resizeHandlerDiv);
	
	// update position of resizeHandler
	if(isOfType(currentObject,'span')){
		//alert('span');
	}else{
		/*var newTop = Util.getAncestorTop(currentObject) + parseInt(currentObject.style.height.replace("px",""),10);
		var newLeft = Util.getAncestorLeft(currentObject) + parseInt(currentObject.style.width.replace("px",""),10);
		resizeHandlerDiv.style.top = newTop + "px";
		resizeHandlerDiv.style.left = newLeft + "px"; */
		resizeHandlerDiv.style.top = currentObject.style.height;
		resizeHandlerDiv.style.left = currentObject.style.width; 
	}

	currentMovableObj1 = new Draggable(resizeHandlerDiv, {});
	currentMovableObj = new Draggable(currentObject, {});
	if(currentObject.id != "wrapper"){
		currentObject.style.cursor = "move";
	}
	currentResizableObj = new Resizable(currentObject, {handle: 'resizeHandle'});
}

/*function disableResizable(){
	if(currentResizableObj){ // if box is resizable 
		currentObject.className = "";
		var idToRemove = currentObject.id + "-rzwrap";
		if($(idToRemove)){
			currentObject.style.left = $(idToRemove).style.left;
			currentObject.style.top = $(idToRemove).style.top;
			
			// Removing the main handlers 
			$(idToRemove).parentNode.appendChild($(idToRemove).firstChild);
			$(idToRemove).remove();
			currentObject.style.position = "absolute";
		}
		
		if(currentObject.parentNode.id != "wrapper"){
			currentObject.style.position = "relative";
		}
		
		
		// Removing the hidden controls 
		var elementsToRemove = document.getElementsByClassName('x-unselectable');
		for(var i=0;i<elementsToRemove.length;i++){
			elementsToRemove[i].remove();
		}
		
		currentResizableObj = null;
	}
}

function enableResizable(){
	if(currentObject){
		alert(currentObject.id);
		currentObject.className = "extResizable";
		currentResizableObj = new Ext.Resizable(currentObject.id, {
		            wrap:true,
		            pinned:false,
		            minWidth:10,
		            minHeight: 10,
		            preserveRatio: false,
		            handles: 'all',
		            draggable: true,
		            dynamic: true
		        });
	}
}

function enableOrDisableResize(id){
	Util.hideMenu();
	if(currentResizableObj){ // if box is resizable 
		currentResizableObj.destroy();
		currentResizableObj = null;
		
		$(id).innerHTML = "Change Size";
	}else{
		currentResizableObj = new Resizable(currentObject, {});
		$(id).innerHTML = "Save Size";
	}
}

function enableOrDisableMove(id){
	Util.hideMenu();
	if(currentMovableObj){ //if box is movable
		currentMovableObj.destroy();
		currentMovableObj = null;
		
		$(id).innerHTML = "Move";
	}else{
		if(isOfType(currentObject,'img')){
			currentMovableObj = new Draggable(currentObject.parentNode, {});
		}else{
			currentMovableObj = new Draggable(currentObject, {});
		}
		$(id).innerHTML = "Save Position";
	}
}*/

function setKey(mouse){
	if(mouse.shiftKey)	{
		if(isOfType(currentObject,'div')){	
			$("shiftKeyInfoDiv").style.display = "";
			currentObject.style.cursor = "nw-resize";
			
			enableResize();
		}
	}
}

function releaseKey(mouse){
	if(isOfType(currentObject,'div')){
		$("shiftKeyInfoDiv").style.display = "none";
		currentObject.style.cursor = "default";

		disableResize();
	}
}


/* ******************************************************
 * 	PROPERTIES PANEL
 * *****************************************************/

function hideProperties(){
	$('divAttributes', 'imgAttributes','txtAttributes','pageAttributes','attributesWrapper').invoke('hide');
}

function attributesEdit(type){
	Util.hideMenu();
	$('attributesWrapper').hide();
	//$('attributesWrapper').style.display = 'none';
	var efff1 = new Effect.Appear($('attributesWrapper'));

	//$('propertiestab').show();
	$('footer_container').show();
	
	if(type == 'div'){
		getMargin();
		attributesDisplay(currentObject);
	}else if (type == 'text'){
		textAttributesDisplay(currentObject);
	}else if (type == 'image'){
		imgAttributesDisplay(currentObject);
	}else if(type == 'page'){
		pageAttributesDisplay(currentObject);
	}
	$('colorSelectorNew').hide();
	$('moreLink').show();
	$('moreLink_less').hide();
	$('moreLink_more').show();
}

/*******************************************************************************************
				PAGE PROPERTIES HANDLERS
*******************************************************************************************/				
function pageAttributesDisplay(object){
	$("pageAttributes.title").value = document.title;
	/*$("pageAttributes.left").value = "0pt";
	$("pageAttributes.top").value = "0pt";
	if(document.body.style.marginLeft != ""){
		$("pageAttributes.left").value = document.body.style.marginLeft;
	}
	if(document.body.style.marginTop != ""){
		$("pageAttributes.top").value = document.body.style.marginTop;
	}*/
	if(document.body.style.backgroundColor){
		$("pageAttributes.backgroundColor").value = document.body.style.backgroundColor;
		$("pageAttributes.backgroundColor.color").style.backgroundColor = document.body.style.backgroundColor;
	}else{
		$("pageAttributes.backgroundColor").value = $('wrapper').style.backgroundColor;
		$("pageAttributes.backgroundColor.color").style.backgroundColor = $('wrapper').style.backgroundColor;
	}

	//page background image
  	var bgImgText = document.body.style.backgroundImage;
	if(bgImgText.indexOf("url",0) == -1){ //if no bg img
		//resetBGFileInput('page');
	}else{
		//hiding the Bg image seletion option
		$("pageAttributes.bgImage").hide();
		$('pageAttributes.bgRepeat').hide();
		//$("pageAttributes.bgRepeat").value = getBGRepeatValue();
	}

  	//hide other elements' attributes
	$('divAttributes').hide();
	$('imgAttributes').hide();
	$('txtAttributes').hide();
	$('css_properties_control_panel').hide();
	
	//show this object's attributes
	$('attributesWrapper').show();
	$('pageAttributes').show();

	return false ;
}

function pageAttributesSet() { 
    /* UPDATING THE PAGE TITLE */
	document.title = $("pageAttributes.title").value;
	
	if(Util.getBrowser().indexOf("NN") != -1){ //if not ie
		var titleTxtNode = document.createTextNode(document.title);
		var titleNode = $("dot_page_title");
		titleNode.replaceChild(titleTxtNode,titleNode.firstChild);
	}
	
	/* ********************************  */
	/*
	document.body.style.marginLeft = $("pageAttributes.left").value;
	document.body.style.marginTop = $("pageAttributes.top").value; */
	//background image and color
	//alert($("pageAttributes.bgImage").value);
	
	if($("pageAttributes.bgImage").value !== "")
	{
		var bgImgVal = Util.stringReplaceAll($("pageAttributes.bgImage").value, "\\", "//");
		document.body.style.backgroundImage = "url(file://" + bgImgVal + ")";
		document.body.style.backgroundRepeat = $('pageAttributes.bgRepeat').value;
		//document.body.style.background = $("pageAttributes.backgroundColor").value +" url(file://" + bgImgVal + ")";
		//hiding the Bg image seletion option
		//$("pageAttributes.bgImage").hide();
		
		//updating the bg repeat value
		//updateBGRepeatValue($("pageAttributes.bgRepeat").value);
	}else{ /*if no there is no value for bg image */
		document.body.style.backgroundImage = "";
	}
	document.body.style.backgroundColor = $("pageAttributes.backgroundColor").value;
}

function updateBGRepeatValue(value){
	var bgText = ""+document.body.style.background;
	//alert("before update = "+bgText);
	//alert(value);
	if(document.body.style.background.indexOf("no-repeat") != -1){ // if no-repeat found
		//bgText = Util.stringReplaceAll(bgText, "no-repeat",value);
		bgText.replace("no-repeat",value);
	}else if(document.body.style.background.indexOf("repeat-x") != -1){ // if repeat-x found
		//bgText = Util.stringReplaceAll(bgText, "repeat-x",value);
		bgText.replace("repeat-x",value);
	}else if(document.body.style.background.indexOf("repeat-y") != -1){ // if repeat-y found
		//bgText = Util.stringReplaceAll(bgText, "repeat-y",value);
		bgText.replace("repeat-y",value);
	}else if(document.body.style.background.indexOf("repeat") != -1){ // if repeat found
		bgText.replace("repeat",value);
	}
	document.body.style.background = bgText;
	//alert("after update = "+bgText);
	//alert(document.body.style.background.indexOf("repeat"));
}

function getBGRepeatValue(){
	if(document.body.style.background.indexOf("no-repeat") != -1){ // if no-repeat found
		return "no-repeat";
	}else if(document.body.style.background.indexOf("repeat-x") != -1){ // if repeat-x found
		return "repeat-x";
	}else if(document.body.style.background.indexOf("repeat-y") != -1){ // if repeat-y found
		return "repeat-y";
	}else if(document.body.style.background.indexOf("repeat") != -1){ // if repeat found
		return "repeat";
	}
	return "";
}

/*******************************************************************************************
				TEXT PROPERTIES HANDLERS
*******************************************************************************************/				
function textAttributesDisplay(object){
	$("txtAttributes.txtValue").value = currentObject.innerHTML;	
	$("txtAttributes.font").value = currentObject.style.fontFamily;
	$("txtAttributes.color").value = currentObject.style.color;
	$("txtAttributes.color.col").style.backgroundColor = currentObject.style.color;
	var sizeStr = currentObject.style.fontSize;
	$("txtAttributes.size").value = sizeStr.substr(0,sizeStr.length-2);
	$("txtAttributes.size.unit").value = sizeStr.substr(sizeStr.length-2,sizeStr.length-1);

	if(isOfType(currentObject,'a'))
	{
		$("txtAttributes.link").value = currentObject.href;
		$("txtAttributes.link.target").value = currentObject.target;
	}else{
		$("txtAttributes.link").value = "";
		$("txtAttributes.link.target").value = "";
	}
	
	enableDisableTarget();

  	//hide other elements' attributes
  	$('divAttributes').hide();
  	$('imgAttributes').hide();
	$('pageAttributes').hide();
	$('css_properties_control_panel').hide();
	
	//show this object's attributes
	$('attributesWrapper').show();
  	$('txtAttributes').show();
	
  	return false ;
}

function updateText(){
	var obj = currentObject;

	obj.style.fontFamily = $("txtAttributes.font").value;
	obj.style.fontSize = $("txtAttributes.size").value + $("txtAttributes.size.unit").value;
	obj.style.color = $("txtAttributes.color").value;
	obj.innerHTML = $("txtAttributes.txtValue").value;
}

function boldText(){
	var obj = currentObject;
	
	if(obj.style.fontWeight == "bold"){
		obj.style.fontWeight = "";
	}else{
		obj.style.fontWeight = "bold";
	}
}


function italicText(){
	var obj = currentObject;
	
	if(obj.style.fontStyle == "italic"){
		obj.style.fontStyle = "";
	}else{
		obj.style.fontStyle = "italic";
	}
}

function convertTextToLink(num){
	Util.hideMenu();
	var i;
	if(num == 1)
	{
		if($('txtAttributes.link').value !== "") //if a valid link, convert span to anchor
		{
			newLink = document.createElement('a');
			
			newLink.innerHTML = currentObject.innerHTML; //converting the text in span to text in anchor
			currentObject.innerHTML = ""; //clearing the text in span
			
			//copying the attributes of span to anchor
			var spanAttributes=currentObject.attributes;
			for (i = 0; i < spanAttributes.length; i++) {
				newLink.setAttribute(spanAttributes[i].name, spanAttributes[i].value);
			}
			
			newLink.setAttribute('href',$('txtAttributes.link').value);
			newLink.setAttribute('target',$('txtAttributes.link.target').value);
			
			anchorCounter = anchorCounter + 1;
			newLink.setAttribute('id','anchor'+anchorCounter);
			
			//replacing span with anchor
			currentObject.parentNode.replaceChild(newLink,currentObject);
			currentObject = newLink;

		}else{ //if link is empty, convert anchor to span
			newSpan = document.createElement('span');
			
			newSpan.innerHTML = currentObject.innerHTML; //converting the text in anchor to text in span
			currentObject.innerHTML = ""; //clearing the text in span
			
			//copying the attributes of span to anchor
			var linkAttributes=currentObject.attributes;
			for (i = 0; i < linkAttributes.length; i++) {
				if(linkAttributes[i].name != "href" && linkAttributes[i].name != "target") {
					newSpan.setAttribute(linkAttributes[i].name, linkAttributes[i].value);
				}
			}
						
			spanCounter = spanCounter + 1;
			newSpan.setAttribute('id','span'+spanCounter);
			
			//replacing anchor with span
			currentObject.parentNode.replaceChild(newSpan,currentObject);
			currentObject = newSpan;
		}
	}else{ //update target
		currentObject.target = $('txtAttributes.link.target').value;
	}
}

function enableDisableTarget(){
	var attrStr="";
	if (isOfType(currentObject,'img')){
		attrStr = "imgAttributes.link";
	}
	else if(isOfType(currentObject,'a') || isOfType(currentObject,'span')){
		attrStr = "txtAttributes.link";
	}
	
	if($(attrStr) && $(attrStr).value !== "" ){
		$(attrStr+'.target').disabled = "";
	}else{
		$(attrStr+'.target').value = "";
		$(attrStr+'.target').disabled = "disabled";
	}	
}

/*******************************************************************************************
				IMAGE PROPERTIES HANDLERS
*******************************************************************************************/	
function imgAttributesDisplay(object){
  	$("imgAttributes.source").value = currentObject.attributes.getNamedItem('src').value;
  	$("imgAttributes.alt").value = currentObject.attributes.getNamedItem('alt').value;
  	$("imgAttributes.border").value = currentObject.attributes.getNamedItem('border').value;
  	$("imgAttributes.width").value = currentObject.width;
  	$("imgAttributes.height").value = currentObject.height;
	$("imgAttributes.left").value = currentObject.parentNode.style.left;
  	$("imgAttributes.top").value = currentObject.parentNode.style.top;
  
	//hide other elements' attributes
  	$('divAttributes').hide();
	$('txtAttributes').hide();
	$('pageAttributes').hide();
	$('css_properties_control_panel').hide();
	
	//show this object's attributes
	$('attributesWrapper').show();
  	$('imgAttributes').show();
	
  	return false ;
}

function updateImgAttributes(){
	currentObject.width = $("imgAttributes.width").value;
	currentObject.height = $("imgAttributes.height").value;
	currentObject.parentNode.style.left = $("imgAttributes.left").value;
  	currentObject.parentNode.style.top = $("imgAttributes.top").value;
	currentObject.attributes.getNamedItem('border').value = $("imgAttributes.border").value;
	currentObject.attributes.getNamedItem('alt').value = $("imgAttributes.alt").value;
}

function convertImgToLink(num){
	Util.hideMenu();
	if(num == 1)
	{
		if($('imgAttributes.link').value !== "") //if a valid link, add anchor as parent of img
		{
			newLink = document.createElement('a');
			
			newLink.setAttribute('href',$('imgAttributes.link').value);
			newLink.setAttribute('target',$('imgAttributes.link.target').value);
			
			anchorCounter = anchorCounter + 1;
			newLink.setAttribute('id','anchor'+anchorCounter);
			
			var imgNode = currentObject;
			currentObject.parentNode.replaceChild(newLink,currentObject);
			newLink.appendChild(currentObject); //<a> <img></img> </a>
			currentObject = imgNode;
		}else{ //if link is empty, remove the anchor tag and update parent-child node link
			if(!isOfType(currentObject,'img'))
			{
				tmpImg = currentObject.cloneNode(true);
			
				currentObject.parentNode.parentNode.replaceChild(tmpImg,currentObject.parentNode);
				currentObject = tmpImg;
			}
		}
	}else{ //update target
		currentObject.parentNode.target = $('imgAttributes.link.target').value;
	}
}

/*******************************************************************************************
				DIV PROPERTIES HANDLERS
*******************************************************************************************/

function attributesDisplay(object){ 
  var attributesDiv = $('divAttributes'); 
  $("attributes.action").value = currentObject.attributes.getNamedItem('action').value;  
  $("attributes.divID").innerHTML = currentObject.id;
  $("attributes.left").value = currentObject.style.left;
  $("attributes.top").value = currentObject.style.top;
  $("attributes.width").value = currentObject.style.width;
  $("attributes.height").value = currentObject.style.height;
  $("attributes.zindex").value = currentObject.style.zIndex;
  $("attributes.backgroundColor").value = currentObject.style.backgroundColor;
  $("attributes.backgroundColor.color").style.backgroundColor = currentObject.style.backgroundColor;
  $("attributes.name").value = currentObject.attributes.getNamedItem('name').value;
  $("attributes.divInnerHTMLValue").value = currentObject.innerHTML.replace(/%5C/g, "/");

  	//background image
  	var bgImgText = currentObject.style.background;

	if(bgImgText.indexOf("url",0) == -1){ //if no bg img
		//$("attributes.bgImage").value = "";
		resetBGFileInput('div');
	}else{
		//$("attributes.bgImage").value = bgImgText;
		
		//hiding the Bg image seletion option
		$("attributes.bgImage").hide();
	}

  	//Util.placeAtClick(attributesDiv,e);
  	
	//hide other elements' attributes
  	$('imgAttributes').hide();
	$('txtAttributes').hide();
	$('pageAttributes').hide();
	$('css_properties_control_panel').hide();
	
	//show this object's attributes
	$('attributesWrapper').show();
  	$('divAttributes').show();
	
  	return false ;
}

function clearBGVal(objType){
	if(objType == 'div')
	{
		currentObject.style.background = "";
		resetBGFileInput('div');
		currentObject.style.backgroundColor = $("attributes.backgroundColor").value;
		//attributeSet();
	}
	else if(objType == 'page')
	{
		document.body.style.background = "";
		resetBGFileInput('page');
		//document.body.style.backgroundColor = $("pageAttributes.backgroundColor").value;
		//attributeSet();
	}
}

function executeAction(){
	eval(currentObject.attributes.getNamedItem('action').value);
}

function attributesSet() {
  	currentObject.attributes.getNamedItem('action').value = $("attributes.action").value;  
   currentObject.style.left = $("attributes.left").value;
   currentObject.style.top = $("attributes.top").value;
   currentObject.style.zIndex = $("attributes.zindex").value;
   currentObject.style.width = $("attributes.width").value;
   currentObject.style.height = $("attributes.height").value;
   
   currentObject.attributes.getNamedItem('name').value = $("attributes.name").value;
   currentObject.innerHTML = $("attributes.divInnerHTMLValue").value;
   name2id[$("attributes.name").value] = currentObject.attributes.getNamedItem('id').value;

	//background image and color
	if($("attributes.bgImage").value !== "")
	{	
		var bgImgVal = Util.stringReplaceAll($("attributes.bgImage").value, "\\", "//");
		currentObject.style.background = $("attributes.backgroundColor").value +
						" url(file://" + bgImgVal + ")";
		//hiding the Bg image seletion option
		$("attributes.bgImage").style.display = "none";
	}else{
		currentObject.style.background = "";
		currentObject.style.backgroundColor = $("attributes.backgroundColor").value;
	}
						
   //$('divAttributes').style.display = "none";
}

function attributesCancel() {
   $('divAttributes').style.display = "none";
   Util.toggleDiv('struct');
}

function resetBGFileInput(objectType){
	var newHTML;
	if(objectType == 'div')
	{
		newHTML = "<input name=\"text32\" type=\"file\" id=\"attributes.bgImage\" value=\"\" size=\"20\" onblur=\"attributesSet()\" /><input value=\"Clear BG\" type=\"button\" onmousedown=\"clearBGVal('div');\" />";
		$("td.divBGFile").innerHTML = newHTML;
	}else if(objectType == 'page')
	{
		//var newHTML = "<input name=\"text32\" type=\"file\" id=\"pageAttributes.bgImage\" value=\"\" size=\"20\" onblur=\"pageAttributesSet()\" /><input value=\"Clear BG\" type=\"button\" onmousedown=\"clearBGVal('page');\" /><select onchange=\"pageAttributesSet()\" id=\"pageAttributes.bgRepeat\"><option value=\"repeat\" selected>repeat</option><option value=\"no-repeat\">no-repeat</option><option value=\"repeat-x\">repeat-x</option><option value=\"repeat-y\">repeat-y</option></select>";
		newHTML = "<input name=\"text32\" type=\"file\" id=\"pageAttributes.bgImage\" value=\"\" size=\"20\" onblur=\"pageAttributesSet()\" /><input value=\"Clear BG\" type=\"button\" onmousedown=\"clearBGVal('page');\" />";
		$("td.pageBGFile").innerHTML = newHTML;
	}
}

/*******************************************************************************************
				Generic HANDLERS
*******************************************************************************************/	

function setMargin() {
	var style = currentObject.getAttribute("style");
	
	/*
	//margin bottom
	
	//margin left
	
	
	//margin right
	
	//margin
	if(currentObject.style.margin){
		style += "margin: "+$("attributes.marginAll").value + "px;";
		currentObject.setAttribute("style",style);
	}else{
		currentObject.style.margin = appendPX($("attributes.marginAll").value);
	}
	*/
	
	//alert(style);
}

function updateMarginTop(){
	var style = currentObject.getAttribute("style");
	if(Util.hasStyle(style,"margin-top")){
		currentObject.style.marginTop = appendPX($("attributes.marginTop").value);
	}else{
		style += "margin-top: "+$("attributes.marginTop").value + "px; ";
		currentObject.setAttribute("style",style);
	}
}

function updateMarginBottom(){
	var style = currentObject.getAttribute("style");
	if(Util.hasStyle(style,"margin-bottom")){
		currentObject.style.marginBottom = appendPX($("attributes.marginBottom").value);
	}else{
		style += "margin-bottom: "+$("attributes.marginBottom").value + "px;";
		currentObject.setAttribute("style",style);
	}
	
}
function updateMarginLeft(){
	var style = currentObject.getAttribute("style");
	if(Util.hasStyle(style,"margin-left")){
		currentObject.style.marginLeft = appendPX($("attributes.marginLeft").value);
	}else{
		style += "margin-left: "+$("attributes.marginLeft").value + "px;";
		currentObject.setAttribute("style",style);
	}
}

function updateMarginRight(){
	var style = currentObject.getAttribute("style");
	if(Util.hasStyle(style,"margin-right")){
		currentObject.style.marginRight = appendPX($("attributes.marginRight").value);
	}else{
		style += "margin-right: "+$("attributes.marginRight").value + "px;";
		currentObject.setAttribute("style",style);
	}
}	

function getMargin() {
   $("attributes.marginTop").value = currentObject.style.marginTop;
   $("attributes.marginBottom").value = currentObject.style.marginBottom;
   $("attributes.marginLeft").value = currentObject.style.marginLeft;
   $("attributes.marginRight").value = currentObject.style.marginRight;
   $("attributes.marginAll").value = currentObject.style.margin;
}

function appendPX(txt){
	/*if(txt.indexOf("px") == -1){
		alert("add px");
		txt += "px";
	}*/
	return txt;
}

////////////////////////////////////////////////////////


function pickColor(valueInputID, boxInputID, e){	
	var cs = $('colorSelectorNew');
	var boxCol = $(boxInputID); 
	
	currentBGColorValue = boxInputID;
	currentBGColorBox = valueInputID;
	
	cs.style.top = Event.pointerY(e)-150 + "px";
	cs.style.left = Event.pointerX(e) + "px";

	Util.showDiv('colorSelectorNew');
}


/*
 * Flickr Show Handlers
 */
 
 function addFlickrShow(){
	var flickrID = $('flickrShowPanel_ID').value;
	//alert(flickrID);
	if(flickrID.length > 0){
		var box = addNewBox(currentObject, 300, 500, "", false, true, false);
		box.innerHTML = "<div id=\"fsDemo\" style=\"position:relative; width: 500px; height:300px;\">";
		
		var jsText = "fs1 = new flickrShow(\""+flickrID+"\", \"fsDemo\", \"blue\");";
		var heads = document.getElementsByTagName('head');
		var headText = heads[0].innerHTML;
		headText += "\n<script type=\"text\/javascript\">\n" + jsText + "\n</script>";
		
		heads[0].innerHTML = headText;
	}
	
	$("flickrShowPanel_ID").value = "";
 }
 
 /* ********************************************
   * CTRL C AND V detection
   * *********************************************/
   
var ctrlPressed = false;
var ctrlCPressed = false;
var ctrlVPressed = false;
function keyDown(evt)
{
	if(evt.keyCode == 46){
		//delete key
		if(isAccepted(currentObject)){
			if(confirm('Are you sure you want to delete the item?')){
				deleteBox(null,currentObject);
			}
		}
	}
	if(evt.keyCode == 17){
		ctrlPressed = true;
	}
	else if(evt.keyCode == 67){
		if(ctrlPressed && ctrlCPressed===false){
			ctrlCPressed = true;
			//ctrl + c
			if(isAccepted(currentObject)){
				copyElement();
			}
		}
	}else if(evt.keyCode == 86){
		if(ctrlPressed && ctrlVPressed===false){
			ctrlVPressed = true;
			//ctrl + v
			if(isAccepted(currentObject)){
				pasteElement();
			}
		}
	}
}

function releaseKeys(){
	ctrlPressed = false;
	ctrlCPressed = false;
	ctrlVPressed = false;
}

isRightClick = function isRightClick(e) {
	var rightclick;
	if((Util.getBrowser() == "ie6" || Util.getBrowser() == "ie7" || Util.getBrowser() == "ie7_no_XMLHttpRequest"))
	{
		//alert('IEIEIEI');
	}else{
		//if (e.which) rightclick = (e.which == 3);
		//else if (e.button) rightclick = (e.button == 2);
		rightclick = (e.button == 2);
	}
	return rightclick;
};

/*
 * ADVANCED CSS PROPERTIES PANEL
 */
 
 // Set the Paragraph or List mode when the mouse enters the button
function toggleMode(button) {
	if (button.id == 'listbutton') {
		sandboxAsList(currentObject.id);
		document.getElementById('parabutton').className = '';
	} else {
		sandboxAsPara(currentObject.id);
		document.getElementById('listbutton').className = '';
	}
	//button.className = 'active';
}

// Converts each sentence of the sandbox text to a list item
function sandboxAsList(divID) {
	var text = document.getElementById(divID).innerHTML;
	if (text.charAt(0) == '<') { return; } // already done 
	var listed = '<ul><li>' + text.replace(/\./g, '.</li><li>') + '</li></ul>';
	listed = listed.replace(/<li>\s*<\/li>/, ''); // remove empty item
	document.getElementById(divID).innerHTML = listed;
}

// Converts the list of items to a paragraph
function sandboxAsPara(divID) {
	var text = document.getElementById(divID).innerHTML;
	if (text.charAt(0) != '<') { return; } // already done
	$(divID).innerHTML = text.stripTags();
}

// The function is called whenever the user clicks some property.  It applies the property to the div
function convertLiToLink(button) {
	try {
	divID = currentObject.id;
		/* Get property name and value */
		var prop = button.parentNode.parentNode.className.camelize();
		var value = button.innerHTML.stripTags().strip(); // strip: IE hates spaces

		if (prop == 'cursor') {
			/* The cursor property is applied to BODY, not Sandbox */
			document.getElementsByTagName('body')[0].style.cursor = value;
		} else {
			// Apply the property to the Sandbox
			$(divID).style[prop] = value;
			// Apply the property to the list (when in list mode)
			if (prop.slice(0,4) == 'list') {
				$(divID).childNodes[0].style[prop] = value;
			}
		}

		// Highlight the clicked property
		// Remove "active" class from all brother nodes then add the current
		// Tip: the LI element (not A) holds the class
		var children = button.parentNode.parentNode.childNodes;
		for (var i = 0; i < children.length; i++) { children[i].className = ''; }
		//button.parentNode.className = 'active';
	} catch(e) {}
}

var myJSONObject = { "cssProperties":	[	{
											"name": "font",
											"children" :	[
																{ "name" : "font-family",
																  "value": ["Verdana","Arial","Times","Courier","sans-serif","serif","monospace","cursive","fantasy"]
																},
																{ "name" : "font-size",
																  "value": ["xx-small","x-small","small","medium","large","x-large","xx-large","smaller","larger","8pt","10pt","12pt","14pt","16pt","50%","75%","100%","150%"]
																},
																{ "name" : "font-style",
																  "value": ["normal","italic","oblique"]
																},
																{ "name" : "font-variant",
																  "value": ["normal","small-caps"]
																},
																{ "name" : "font-weight",
																  "value": ["normal","bold","bolder","lighter"]
																},
																{ "name" : "color",
																  "value": [ "#ff9900","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow"]
																}
															]
											},
											{
											"name": "background",
											"children" :	[
																{ "name" : "background-color",
																  "value": ["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow","transparent"]
																},
																{ "name" : "background-image",
																  "value": ["none","url(image.gif)"]
																},
																{ "name" : "background-repeat",
																  "value": ["repeat","repeat-x","repeat-y","no-repeat"]
																},
																{ "name" : "background-position",
																  "value": ["left","right","top","bottom","center"]
																},
																{ "name" : "background-attachment",
																  "value": ["scroll","fixed"]
																}
															]
											},
											{
											"name": "border",
											"children" :	[
																{	"name" : "border-color",
																	"value": ["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow","transparent"]
																},
																{	"name" : "border-style",
																	"value": ["none","solid","double","dashed","dotted","groove","ridge","inset","outset"]
																},
																{	"name" : "border-width",
																	"value": ["thin","medium","thick","0","1px","2px","5px","10px","0.5em","1em","2em"]
																}
															]
											},
											{
											"name": "text",
											"children" :	[
																{	"name" : "text",
																	"value": ["&nbsp;A&nbsp;","&nbsp;1.&nbsp;"]
																},
																{	"name" : "text-align",
																	"value": ["left","right","center","justify"]
																},
																{	"name" : "text-decoration",
																	"value": ["none","underline","overline","line-through","blink"]
																},
																{	"name" : "text-transform",
																	"value": ["none","capitalize","uppercase","lowercase"]
																},
																{	"name" : "text-indent",
																	"value": ["0","1em","2em","5em","-2em"]
																},
																{	"name" : "overflow",
																	"value": ["auto","visible","hidden","scroll"]
																}
															]
											},
											{
											"name": "position",
											"children" :	[
																{	"name" : "top",
																	"value": ["auto","0","40px","25%"]
																},
																{	"name" : "bottom",
																	"value": ["auto","0","40px","25%"]
																},
																{	"name" : "left",
																	"value": ["auto","0","40px","25%"]
																},
																{	"name" : "right",
																	"value": ["auto","0","40px","25%"]
																},
																{	"name" : "float",
																	"value": ["none","left","right"]
																},
																{	"name" : "position",
																	"value": ["static","relative","absolute","fixed"]
																}
															]
											},
											{
											"name": "list",
											"children" :	[
																{	"name" : "list-style-type",
																	"value": ["none","disc","circle","square","decimal","decimal-leading-zero","lower-roman","upper-roman","lower-alpha","upper-alpha","lower-latin","upper-latin","lower-greek"]
																},
																{	"name" : "list-style-image",
																	"value": ["none","url(image.gif)"]
																},
																{	"name" : "list-style-position",
																	"value": ["inside","outside"]
																}
															]
											},
											{
											"name": "para",
											"children" :	[
																{	"name" : "line-height",
																	"value": ["normal","150%","50%"]
																},
																{	"name" : "letter-spacing",
																	"value": ["normal",".2em",".5em","1em","-.1em"]
																},
																{	"name" : "word-spacing",
																	"value": ["normal",".5em","1em","2em","-.5em"]
																},
																{	"name" : "white-space",
																	"value": ["normal","pre","nowrap"]
																},
																{	"name" : "direction",
																	"value": ["ltr","rtl"]
																}
															]
											},
											{
											"name": "dimensions & margins",
											"children" :	[
																{	"name" : "width",
																	"value": ["auto","50%","75%","100%"]
																},
																{	"name" : "height",
																	"value": ["auto","50px","100px","200px","50%"]
																},
																{	"name" : "padding",
																	"value": ["0","1em","2em","3em","4em","5em","1px","5px","10px","25px","50px"]
																},
																{	"name" : "margin",
																	"value": ["auto","0","1em","5em"]
																}
															]
											},
											{
											"name": "views & misc",
											"children" :	[
																{	"name" : "visibility",
																	"value": ["visible","hidden"]
																},
																{	"name" : "display",
																	"value": ["none","block","inline","list-item","run-in","inline-block","inline-table","table","table-cell"]
																},
																{	"name" : "cursor",
																	"value": ["auto","crosshair","default","pointer","hand","move","text","wait","progress","help","e-resize","n-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize"]
																}
															]
											}
										]
					};

function populateSelectList(selectListID, objArray, stage){
	clearSelectList(selectListID);
	clearSelectList('cssPropertiesValuesTD');
	var list1Object = $(selectListID);
	list1Object.style.height = "100px";
	for(var i=0; i<objArray.length; i++)
	{

		var li = document.createElement('li');		
		switch(stage){
			case 1: li.setAttribute('onmouseover', 'step2('+i+');');
					break;
			case 2: 
					li.setAttribute('onmouseover', 'step3('+i+',\''+objArray[i].name+'\',\''+objArray[i].value+'\');');
					break;
		}
		
		li.innerHTML = objArray[i].name;
		list1Object.appendChild(li);
	}
}

function clearSelectList(selecListID){
	var list = $(selecListID);
	list.innerHTML = "";
	list.style.height = "";
}

function step2(index){
	populateSelectList('cssPropertiesSelect2',myJSONObject.cssProperties[index].children,2);
}

function step3(index, name, value){
	$('cssPropertiesValuesTD').style.height = "100px";
	$('cssPropertiesValuesTD').innerHTML ="";
	var tokens = value.split(',');
	var ul = document.createElement('ul');
	ul.setAttribute('class',name);
	for(var i=0;i<tokens.length;i++){
		var li = document.createElement('li');
		var anchor = document.createElement('a');
		anchor.setAttribute('onClick','convertLiToLink(this);');
		anchor.innerHTML = tokens[i];
		li.appendChild(anchor);
		ul.appendChild(li);
	}
	$('cssPropertiesValuesTD').appendChild(ul);
}

function init_cssPropertiesControlPanel(){
	populateSelectList('cssPropertiesSelect1',myJSONObject.cssProperties,1);
	/*$('divAttributes').hide();
	$('imgAttributes').hide();
	$('txtAttributes').hide();
	$('pageAttributes').hide();*/
	//$('css_properties_control_panel').show();
	var eff24 = new Effect.Appear($('css_properties_control_panel'));
	$('moreLink_more').hide();
	$('moreLink_less').show();
}

function close_cssPropertiesControlPanel(){
	$('css_properties_control_panel').hide();
	$('moreLink_more').show();
	$('moreLink_less').hide();
}

function loadCalendar(){
	Load("../../boot/Loader.js");
	Load("../../lang/System.js");
	Load("../../lang/Naming.js");
	Load("../../lang/Construct.js");
	Load("../../lang/Method.js");
	Load("../../lang/Class.js");
	Load("../../lang/ClassBuilder.js");
	Load("../../lang/Namespace.js");
	Load("../../lang/Interface.js");
	Load("../../lang/InterfaceBuilder.js");
	Load("../../lang/Enum.js");
	Load("../../lang/EnumBuilder.js");
	Load("../../lang/Reflect.js");
	Load("../../lang/JSON.js");
	Load("../../lang/Exception.js");
	Load("../../lang/CastException.js");
	Load("../../lang/UnimplementedException.js");
	Load("../../lang/UnsupportedException.js");
	Load("../../lang/InvalidOpException.js");
	Load("../../lang/ArgumentException.js");
	Load("../../lang/ArgTypeException.js");
	Load("../../lang/ArgFormatException.js");
	Load("../../lang/ArgRangeException.js");
	Load("../../lang/ArgNullException.js");

	tc.lang.Namespace.build(this,"tc.debug");
	tc.lang.Namespace.build(this,"tc.util");
	tc.lang.Namespace.build(this,"tc.io");
	tc.lang.Namespace.build(this,"tc.io.provider");
	tc.lang.Namespace.build(this,"tc.io.virtual");
	tc.lang.Namespace.build(this,"tc.platform");
	tc.lang.Namespace.build(this,"tc.platform.browser");
	tc.lang.Namespace.build(this,"tc.platform.activex");
	tc.lang.Namespace.build(this,"tc.platform.activex.io");
	tc.lang.Namespace.build(this,"tc.platform.xpcom");
	tc.lang.Namespace.build(this,"tc.platform.xpcom.io");
	tc.lang.Namespace.build(this,"tc.core");
	tc.lang.Namespace.build(this,"tc.app.messenger");

	Load("../../debug/test.js");
	Load("../../debug/demotest.js");
	Load("../../debug/log.js");
	Load("../../debug/logdemo.js");
	Load("../../util/String.js");
	Load("../../util/Random.js");

	Load("../../io/Attribute.js");
	Load("../../io/IOException.js");
	Load("../../io/EOSException.js");
	Load("../../io/EOFException.js");
	Load("../../io/Reader.js");
	Load("../../io/Writer.js");
	Load("../../io/PrintWriter.js");
	Load("../../io/BasicReader.js");
	Load("../../io/BasicWriter.js");
	Load("../../io/StringReader.js");
	Load("../../io/StringWriter.js");
	Load("../../io/LineWriter.js");
	Load("../../io/Pipe.js");
	Load("../../io/provider/File.js");
	Load("../../io/provider/FileReader.js");
	Load("../../io/provider/FileWriter.js");
	Load("../../io/provider/Provider.js");
	Load("../../io/File.js");
	Load("../../io/FileReader.js");
	Load("../../io/FileWriter.js");
	Load("../../io/JointCallback.js");
	Load("../../io/MountPoint.js");
	Load("../../io/MountTree.js");
	Load("../../io/Utilities.js");
	Load("../../io/FileSystem.js");
	Load("../../io/virtual/File.js");
	Load("../../io/virtual/FileReader.js");
	Load("../../io/virtual/FileWriter.js");
	Load("../../io/virtual/Provider.js");

	Load("../../platform/browser/Console.js");
	Load("../../platform/browser/CSS.js");
	Load("../../platform/browser/Event.js");
	Load("../../platform/browser/XmlDom.js");
	Load("../../platform/activex/io/File.js");
	Load("../../platform/activex/io/RootFile.js");
	Load("../../platform/activex/io/FileReader.js");
	Load("../../platform/activex/io/FileWriter.js");
	Load("../../platform/activex/io/Provider.js");
	Load("../../platform/xpcom/io/File.js");
	Load("../../platform/xpcom/io/RootFile.js");
	Load("../../platform/xpcom/io/FileReader.js");
	Load("../../platform/xpcom/io/FileWriter.js");
	Load("../../platform/xpcom/io/Provider.js");

	Load("../../core/Scheduler.js");
	Load("../../core/Task.js");
	Load("../../core/Application.js");
	Load("../../core/Process.js");
	Load("../../core/Init.js");

	Load("../interp/CommandInterp.js");
	Load("../interp/Command.js");
	Load("../../io/filels.js");
	Load("../../../test/testfiles.js");
	Load("../tiddlywiki/JsonRpcPlugin.js");
	Load("../tiddlywiki/TiddlyWiki.js");
	Load("../tiddlywiki/internal.js");
	Load("../tiddlywiki/Command.js");
	Load("../tiddlywiki/VersionControl.js");

	Load("../../../dojo/dojo.messenger.js");
	Load("../messenger/Messenger.js");
	Load("../messenger/MessengerPlugin.js");

	Load("../calendar/CalManager.js");
	Load("../calendar/AlarmMgr.js");
	Load("../calendar/ApptMgr.js");
	Load("../calendar/Calendar.js");
	Load("../calendar/Command.js");
	Load("../calendar/DateSelector.js");
	Load("../calendar/EventScheduler.js");
	Load("../validator/Validator.js");
	Load("../calendar/jt_.js");
	Load("../calendar/jt_DialogBox.js");
	
}

function addCalendar(){
	//addCalendarHeader();
	tc.app.tiddlywiki.TiddlyWiki.init();
	tc.app.calendar.CalManager.init();
	loadOptionsCookie();

	document.getElementById("tiddlywiki").style.display = 'none';
	tc.app.interp.Command.showAllCal();
	
	//moveCalendarToDiv();
}

function addCalendarHeader(){
	var hdr = '<link rel="stylesheet" type="text/css" href="../calendar/calendar.css"><link rel="stylesheet" type="text/css" href="../calendar/jt_DialogBox.css"><link rel="stylesheet" type="text/css" href="../calendar/veils.css"><link rel="stylesheet" type="text/css" href="../messenger/messenger.css"><script type="text/javascript" src="./js/lib/com.iskitz.ajile.0.9.9.2.js"></script>';
	var heads = document.getElementsByTagName('head');
	var headText = heads[0].innerHTML;
	headText += hdr;
	heads[0].innerHTML = headText;
}

function moveCalendarToDiv(){
	var divIDs = ['tiddlywiki','eventDiv','recurrDiv','pollDiv','psDiv','context','listview','detailview','calendar','summaryview','weekview'];
	
	var bgBox = addNewBox($('wrapper'), 120, 120, "", true, false,false);
	for(var i=0;i<divIDs.length;i++){
		//alert(divIDs[i] + " is " + $(divIDs[i]));
		if($(divIDs[i])){
			var tempDiv = $(divIDs[i]);
			$(divIDs[i]).remove();
			bgBox.appendChild(tempDiv);
		}
	}
}